#pragma once
#include"Slist.h"

SLN* CreatNewNode(SlistDataType x)
{
	SLN *newnode = (SLN*)malloc(sizeof(SLN));
	if (newnode == NULL)
	{
		printf("malloc failed!\n");
		return NULL;
	}
	newnode->Data = x;
	newnode->next = NULL;
	return newnode;
}

void SLTPushBack(SLN** PPhead, SlistDataType x)
{
	SLN *newnode = CreatNewNode(x);
	if (*PPhead == NULL)
	{
		*PPhead = newnode;
	}
	else
	{
		SLN* tail = *PPhead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}
		tail->next = newnode;
	}
}

void SLTPrint(SLN* Phead)
{
	while (Phead != NULL)
	{
		printf("%c ", Phead->Data);
		Phead = Phead->next;
	}
}

void SLTPushFront(SLN** PPhead, SlistDataType x)
{
	SLN* newnode = CreatNewNode(x);
	newnode->next = *PPhead;
	*PPhead = newnode;
}

void SLTPopBack(SLN** PPhead)
{
	SLN* tail = *PPhead;
	SLN* prev = *PPhead;
	while (tail->next != NULL)
	{
		prev = tail;
		tail = tail->next;
	}
	prev->next = NULL;
	free(tail);
}

void SLTPopFront(SLN** PPhead)
{
	SLN* prev = (*PPhead)->next;
	free(*PPhead);
	*PPhead = prev;
}

SLN* SLTDataFind(SLN* Phead, SlistDataType x)
{
	SLN* pos = Phead;
	while (pos != NULL)
	{
		if (pos->Data == x)
		{
			return pos;
		}
		pos = pos->next;
	}
	return NULL;
}

void SLTInsert(SLN** PPhead, SLN* pos, SlistDataType x)
{
	if ((*PPhead)->next == NULL)
	{
		SLTPushFront(PPhead,x);
	}
	else
	{
		SLN* newnode = CreatNewNode(x);
		SLN* prev = *PPhead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		newnode->next = pos;
		prev->next = newnode;
	}
}

void SLTErase(SLN** PPhead, SLN* pos)
{
	if ((*PPhead)->next == NULL)
	{
		SLTPopFront(PPhead);
	}
	else
	{
		SLN* prev = *PPhead;
		while (prev->next != pos)
		{
			prev = prev->next;
		}
		prev->next = pos->next;
		free(pos);
	}
}